package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.base.domain.User;
import cn.wolfcode.car.base.service.IUserService;
import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.domain.CarPackageAudit;
import cn.wolfcode.car.business.domain.ServiceItem;
import cn.wolfcode.car.business.mapper.ServiceItemMapper;
import cn.wolfcode.car.business.query.ServiceItemQuery;
import cn.wolfcode.car.business.service.IBpmnInfoService;
import cn.wolfcode.car.business.service.ICarPackageAuditService;
import cn.wolfcode.car.business.service.IServiceItemService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.github.pagehelper.PageHelper;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class ServiceItemServiceImpl implements IServiceItemService {

    @Autowired
    private ServiceItemMapper serviceItemMapper;
    @Autowired
    private ICarPackageAuditService carPackageAuditService;
    @Autowired
    private IBpmnInfoService bpmnInfoService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private IUserService userService;

    @Override
    public TablePageInfo<ServiceItem> query(ServiceItemQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<ServiceItem>(serviceItemMapper.selectForList(qo));
    }

    @Override
    public void save(ServiceItem serviceItem) {
        serviceItemMapper.insert(serviceItem);
    }

    @Override
    public ServiceItem get(Long id) {
        return serviceItemMapper.selectByPrimaryKey(id);
    }


    @Override
    public void update(ServiceItem serviceItem) {
        ServiceItem oldObj = this.get(serviceItem.getId());
        //非套餐不用处理
        //已上架,不能编辑,抛异常
        if (oldObj.getSaleStatus() == 1) {
            throw new BusinessException("服务处于上架中,不能编辑");
        }
        //套餐,审核中,不能编辑,抛异常
        if (oldObj.getCarPackage() == 1 && oldObj.getAuditStatus() == 1) {
            throw new BusinessException("服务是套餐且处于审核中,不能编辑");
        }
        //套餐,审核通过后再编辑,初始化并重新发起审核
        if (oldObj.getCarPackage() == 1 && oldObj.getAuditStatus() == 2) {
            serviceItem.setAuditStatus(0);
        } else {
            serviceItem.setAuditStatus(oldObj.getAuditStatus());
        }
        if (serviceItem.getCarPackage() == 1) {
            serviceItem.setAuditStatus(0);
        }
        if (serviceItem.getCarPackage() == 0) {
            serviceItem.setAuditStatus(4);
        }
        serviceItemMapper.updateByPrimaryKey(serviceItem);
    }

    @Override
    public void deleteBatch(String ids) {
        Long[] dictIds = Convert.toLongArray(ids);
        for (Long dictId : dictIds) {
            serviceItemMapper.deleteByPrimaryKey(dictId);
        }
    }

    @Override
    public List<ServiceItem> list() {
        return serviceItemMapper.selectAll();
    }

    @Override
    public void OnSaleStatus(Long id, ServiceItem serviceItem) {
        //1.如果已上架就不需要再进行上架
        ServiceItem oldObj = this.get(id);
        if (ServiceItem.SALESTATUS_ON.equals(oldObj.getSaleStatus())) {
            throw new BusinessException("已上架,不需要再进行上架");
        }
        //2.如果是套餐,如果不是审核通过的状态，是不能上架的，抛出异常.
        if (ServiceItem.CARPACKAGE_YES.equals(oldObj.getCarPackage()) &&
                !ServiceItem.AUDITSTATUS_APPROVED.equals(oldObj.getAuditStatus())
        ) {
            throw new BusinessException("套餐审核通过才能上架");
        }
        //3.在数据库中进行状态修改
        serviceItemMapper.changeSaleStatus(id, ServiceItem.SALESTATUS_ON);
    }

    @Override
    public void OffSaleStatus(Long id, ServiceItem serviceItem) {
        serviceItemMapper.changeSaleStatus(id, ServiceItem.SALESTATUS_OFF);
    }

    //发起服务审核
    @Override
    public void startAudit(Long serviceItemId, Long bpmnInfoId, Long director, Long finance, String info) {
        ServiceItem serviceItem = this.get(serviceItemId);
        //合理性校验
        if (!(ServiceItem.AUDITSTATUS_INIT.equals(serviceItem.getAuditStatus())
                || ServiceItem.AUDITSTATUS_REPLY.equals(serviceItem.getAuditStatus()))) {
            throw new BusinessException("服务项状态出于初始化才能进行审核逻辑");
        }
        //修改服务状态，修改为审核中
        serviceItemMapper.changeAuditStatus(serviceItemId, ServiceItem.AUDITSTATUS_AUDITING);
        //封装CarPackageAudit对象(把店长的ID设置审核人)
        CarPackageAudit carPackageAudit = new CarPackageAudit();
        carPackageAudit.setServiceItemId(serviceItemId);//服务项目 ID
        carPackageAudit.setServiceItemName(serviceItem.getName());//服务项目 名字
        carPackageAudit.setServiceItemInfo(serviceItem.getInfo());//服务项目 备注
        carPackageAudit.setServiceItemPrice(serviceItem.getDiscountPrice());//服务项目 折扣价
        carPackageAudit.setCreateTime(new Date());//服务项目 创建时间
        carPackageAudit.setCreator(ShiroUtils.getUser().getUserName());//创建人当前登录用户
        carPackageAudit.setBpmnInfoId(bpmnInfoId);//bpmn Id
        carPackageAudit.setInfo(info);///服务项目 备注
        carPackageAudit.setAuditorId(director);//审核人Id
        User user = userService.get(carPackageAudit.getAuditorId());//根据审核人ID查审核人
        carPackageAudit.setAuditor(user);//设置审核人对象
        //保存CarPackageAudit对象
        carPackageAuditService.save(carPackageAudit);

        //启动流程实例，以金额作为实例参数
        Map<String, Object> map = new HashMap<>();
        if (director != null) {
            map.put("director", director.toString());
        }
        if (finance != null) {
            map.put("finance", finance.toString());
        }
        map.put("discountPrice", serviceItem.getDiscountPrice().longValue());
        BpmnInfo bpmnInfo = bpmnInfoService.get(bpmnInfoId);
        //启动流程
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(bpmnInfo.getActProcessKey(), carPackageAudit.getId().toString(), map);

        //更新记录实例id
        carPackageAudit.setInstanceId(processInstance.getId());
        carPackageAuditService.updateInstanceId(carPackageAudit);
    }

    @Override
    public void changeAuditStatus(Long serviceItemId, Integer auditstatusInit) {
        serviceItemMapper.changeAuditStatus(serviceItemId, ServiceItem.AUDITSTATUS_INIT);
    }
}
